import 'dart:typed_data';

import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:websafe_svg/websafe_svg.dart';

const String prefix = 'https://test-75290.gzc.vod.tencent-cloud.com/middle/assets';
Widget imageFromAsset(
  String asset, {
  Alignment alignment = Alignment.center,
  Color color,
  BoxFit fit = BoxFit.contain,
  double height,
  Key key,
  String package,
  WidgetBuilder placeholderBuilder,
  String semanticsLabel,
  double width,
  ImageFrameBuilder frameBuilder, //无用
}) {
  final String imageUrl = package == null || package.isEmpty ? '$prefix/$asset' : '$prefix/packages/$package/$asset';
  return CachedNetworkImage(
    imageUrl: imageUrl,
    alignment: alignment,
    color: color,
    placeholder: (
      BuildContext context,
      String url,
    ) {
      // web 没有办法调用这个方法
      // return placeholderBuilder(context);
      return Container();
    },
    fit: fit,
    width: width,
  );
}

Widget svgFromAsset(
  String asset, {
  Alignment alignment = Alignment.center,
  Color color,
  bool excludeFromSemantics = false,
  BoxFit fit = BoxFit.contain,
  double height,
  Key key,
  String package,
  WidgetBuilder placeholderBuilder,
  String semanticsLabel,
  double width,
  ImageFrameBuilder frameBuilder,
}) {
  return WebsafeSvg.network(
    '$prefix/packages/$package/$asset',
    alignment: alignment,
    color: color,
    placeholderBuilder: placeholderBuilder,
    fit: fit,
    semanticsLabel: semanticsLabel,
    width: width,
  );
}

///浏览器没有只能使用 memory
Widget svgFromFile({
  String imageUrl,
  double width,
  double height,
  Color color,
  BoxFit fit,
  WidgetBuilder placeholderBuilder,
}) {
  return FutureBuilder<Uint8List>(
    future: _getSvgData(imageUrl),
    builder: (context, snapshot) {
      if (snapshot.hasData && snapshot.data != null) {
        return WebsafeSvg.memory(
          snapshot.data,
          width: width,
          height: height,
          color: color,
          fit: fit,
          placeholderBuilder: (context) {
            return placeholderBuilder(context);
          },
        );
      }
      return placeholderBuilder(context);
    },
  );
}

///todo 加载 file中的svg 资源
Future<Uint8List> _getSvgData(String imageUrl) async {
  // File file = File(imageUrl);
  // if (!file.existsSync()) {
  //   return null;
  // }
  // return file.readAsBytes();
  return null;
}
